<template>
  <div class="profile-container">
    <el-form :model="form" label-width="80px" class="profile-form">
      <el-form-item label="用户名">
        <el-input v-model="form.username" disabled></el-input>
      </el-form-item>
      <el-form-item label="密码">
        <el-input v-model="form.password" show-password></el-input>
      </el-form-item>
      <el-form-item label="年龄">
        <el-input v-model="form.age" type="number"></el-input>
      </el-form-item>
      <el-form-item label="性别">
        <el-select v-model="form.gender" placeholder="请选择性别">
          <el-option label="男" value="Male"></el-option>
          <el-option label="女" value="Female"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">保存修改</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { useUserInfoStore } from '@/stores/userInfo';
import axios from 'axios';

const userInfoStore = useUserInfoStore();
const form = ref({
  username: '',
  password: '',
  age: '',
  gender: ''
});

onMounted(() => {
  form.value.username = userInfoStore.userInfo.username;
  form.value.password = userInfoStore.userInfo.password;
  form.value.age = userInfoStore.userInfo.age;
  // 保证gender为'Male'或'Female'
  form.value.gender = userInfoStore.userInfo.gender === 'Female' ? 'Female' : 'Male';
});

const onSubmit = async () => {
  try {
    const params = new URLSearchParams();
    params.append('id', userInfoStore.userInfo.id);
    params.append('username', form.value.username);
    params.append('password', form.value.password);
    params.append('age', form.value.age);
    params.append('gender', form.value.gender);
    const res = await axios.post('/api/user/update.do', params, {
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
    });
    if (res.data.code === 200) {
      ElMessage.success('修改成功');
      userInfoStore.setUserInfo({ ...userInfoStore.userInfo, ...form.value });
    } else {
      ElMessage.error(res.data.message || '修改失败');
    }
  } catch (e) {
    ElMessage.error('请求失败');
  }
};
</script>

<style scoped>
.profile-container {
  max-width: 400px;
  margin: 40px auto;
  background: #fff;
  padding: 32px 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}
</style>